package com.li.onjava8.concurrent.under.share;

import com.li.onjava8.utils.TimedAbort;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 其中一个任务负责生成偶数，其他任务则负责消费这些数字。在这里，消费者任务
 * 的唯一工作就是检查偶数的有效性。
 */
public class EvenChecker implements Runnable {
    private IntGenerator generator;
    private final int id;

    public EvenChecker(IntGenerator generator, int id) {
        this.id = id;
        this.generator = generator;
    }

    @Override
    public void run() {
        while (!generator.isCanceled()) {
            int val = generator.next();
            if (val%2 != 0) {
                System.out.println(val + "not even!");
                generator.cancel();
            }
        }
    }

    public static void test(IntGenerator gp, int count) {
        List<CompletableFuture<Void>> checker = IntStream.range(0, count)
                .mapToObj(i -> new EvenChecker(gp, i))
                .map(ec -> CompletableFuture.runAsync(ec))
                .collect(Collectors.toList());
        checker.forEach(CompletableFuture::join);
    }

    public static void test(IntGenerator gp) {
        new TimedAbort(4, "No odd number discovered");
        test(gp, 10);
    }


}
